package com.example.question.dp.dp1;

import java.util.Arrays;

/**
 * @link {<a href="https://leetcode.cn/problems/coin-change/">...</a>}
 */
public class Code02_322 {

    public static void main(String[] args) {
        Code02_322 code = new Code02_322();
        System.out.println("code.coinChange(new int[]{1, 2, 5}, 11) = " + code.coinChange(new int[]{1, 2, 5}, 11));
    }

    /**
     * dp[i] = min{dp[i-coin]} +1
     *
     * @param coins
     * @param amount
     * @return
     */
    public int coinChange(int[] coins, int amount) {
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        // 初始化状态数组
        dp[0] = 0;
        for (int coin : coins) {
            if (coin < amount) {
                dp[coin] = 1;
            }
        }
        // 填充状态数组
        for (int i = 0; i <= amount; i++) {
            for (int coin : coins) {
                if (i > coin && dp[i - coin] != Integer.MAX_VALUE && dp[i - coin] + 1 < dp[i]) {
                    dp[i] = dp[i - coin] + 1;
                }
            }
        }
        // 返回目标值
        return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount];
    }
}
